import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Label } from '../ui/label';
import { 
  Users, 
  GraduationCap, 
  UserCheck,
  Search, 
  Plus, 
  Edit,
  Trash2,
  Upload,
  Download,
  RotateCcw,
  Eye
} from 'lucide-react';

interface StudentUser {
  id: string;
  studentId: string;
  name: string;
  department: string;
  major: string;
  grade: string;
  email: string;
  phone: string;
  status: 'active' | 'inactive' | 'suspended';
  enrollDate: string;
}

interface TeacherUser {
  id: string;
  teacherId: string;
  name: string;
  department: string;
  title: string;
  email: string;
  phone: string;
  status: 'active' | 'inactive';
  hireDate: string;
}

export function UserManagement() {
  const [activeTab, setActiveTab] = useState('students');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedDepartment, setSelectedDepartment] = useState('all');
  const [showUserForm, setShowUserForm] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);

  const students: StudentUser[] = [
    {
      id: '1',
      studentId: '2021001001',
      name: '张三',
      department: '计算机科学学院',
      major: '计算机科学与技术',
      grade: '2021级',
      email: 'zhangsan@university.edu.cn',
      phone: '13800138001',
      status: 'active',
      enrollDate: '2021-09-01'
    },
    {
      id: '2',
      studentId: '2021001002',
      name: '李四',
      department: '计算机科学学院',
      major: '软件工程',
      grade: '2021级',
      email: 'lisi@university.edu.cn',
      phone: '13800138002',
      status: 'active',
      enrollDate: '2021-09-01'
    },
    {
      id: '3',
      studentId: '2020001003',
      name: '王五',
      department: '数学学院',
      major: '数学与应用数学',
      grade: '2020级',
      email: 'wangwu@university.edu.cn',
      phone: '13800138003',
      status: 'suspended',
      enrollDate: '2020-09-01'
    }
  ];

  const teachers: TeacherUser[] = [
    {
      id: '1',
      teacherId: 'T2024001',
      name: '陈教授',
      department: '数学学院',
      title: '教授',
      email: 'chenjiaoshou@university.edu.cn',
      phone: '13900139001',
      status: 'active',
      hireDate: '2015-08-15'
    },
    {
      id: '2',
      teacherId: 'T2024002',
      name: '张老师',
      department: '计算机科学学院',
      title: '副教授',
      email: 'zhanglaoshi@university.edu.cn',
      phone: '13900139002',
      status: 'active',
      hireDate: '2018-03-20'
    },
    {
      id: '3',
      teacherId: 'T2024003',
      name: '李老师',
      department: '外语学院',
      title: '讲师',
      email: 'lilaoshi@university.edu.cn',
      phone: '13900139003',
      status: 'inactive',
      hireDate: '2020-09-10'
    }
  ];

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <Badge className="bg-green-100 text-green-800">正常</Badge>;
      case 'inactive':
        return <Badge variant="secondary">停用</Badge>;
      case 'suspended':
        return <Badge variant="destructive">暂停</Badge>;
      default:
        return <Badge variant="outline">未知</Badge>;
    }
  };

  const filteredStudents = students.filter(student => {
    const matchesSearch = student.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         student.studentId.includes(searchTerm);
    const matchesDepartment = selectedDepartment === 'all' || student.department === selectedDepartment;
    return matchesSearch && matchesDepartment;
  });

  const filteredTeachers = teachers.filter(teacher => {
    const matchesSearch = teacher.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         teacher.teacherId.includes(searchTerm);
    const matchesDepartment = selectedDepartment === 'all' || teacher.department === selectedDepartment;
    return matchesSearch && matchesDepartment;
  });

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-medium">用户管理</h1>
        <div className="flex gap-2">
          <Button variant="outline">
            <Download className="mr-2 h-4 w-4" />
            批量导出
          </Button>
          <Button variant="outline">
            <Upload className="mr-2 h-4 w-4" />
            批量导入
          </Button>
          <Button onClick={() => setShowUserForm(true)}>
            <Plus className="mr-2 h-4 w-4" />
            新增用户
          </Button>
        </div>
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">学生总数</p>
                <p className="text-2xl font-medium">{students.length}</p>
              </div>
              <GraduationCap className="h-8 w-8 text-blue-500" />
            </div>
            <p className="text-xs text-green-600 mt-2">
              +{students.filter(s => s.status === 'active').length} 正常状态
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">教师总数</p>
                <p className="text-2xl font-medium">{teachers.length}</p>
              </div>
              <Users className="h-8 w-8 text-green-500" />
            </div>
            <p className="text-xs text-green-600 mt-2">
              +{teachers.filter(t => t.status === 'active').length} 在职教师
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">活跃用户</p>
                <p className="text-2xl font-medium">
                  {students.filter(s => s.status === 'active').length + 
                   teachers.filter(t => t.status === 'active').length}
                </p>
              </div>
              <UserCheck className="h-8 w-8 text-orange-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">院系数量</p>
                <p className="text-2xl font-medium">18</p>
              </div>
              <Users className="h-8 w-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList>
          <TabsTrigger value="students">学生管理</TabsTrigger>
          <TabsTrigger value="teachers">教师管理</TabsTrigger>
        </TabsList>

        <TabsContent value="students" className="space-y-4">
          {/* Search and Filter */}
          <Card>
            <CardContent className="p-4">
              <div className="flex gap-4">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索学生姓名或学号..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                <Select value={selectedDepartment} onValueChange={setSelectedDepartment}>
                  <SelectTrigger className="w-48">
                    <SelectValue placeholder="选择院系" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部院系</SelectItem>
                    <SelectItem value="计算机科学学院">计算机科学学院</SelectItem>
                    <SelectItem value="数学学院">数学学院</SelectItem>
                    <SelectItem value="外语学院">外语学院</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* Students Table */}
          <Card>
            <CardHeader>
              <CardTitle>学生列表</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>学号</TableHead>
                    <TableHead>姓名</TableHead>
                    <TableHead>院系</TableHead>
                    <TableHead>专业</TableHead>
                    <TableHead>年级</TableHead>
                    <TableHead>邮箱</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead>操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredStudents.map((student) => (
                    <TableRow key={student.id}>
                      <TableCell className="font-medium">{student.studentId}</TableCell>
                      <TableCell>{student.name}</TableCell>
                      <TableCell>{student.department}</TableCell>
                      <TableCell>{student.major}</TableCell>
                      <TableCell>{student.grade}</TableCell>
                      <TableCell className="text-sm">{student.email}</TableCell>
                      <TableCell>{getStatusBadge(student.status)}</TableCell>
                      <TableCell>
                        <div className="flex space-x-2">
                          <Button variant="ghost" size="sm">
                            <Eye className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => {
                            setEditingUser(student);
                            setShowUserForm(true);
                          }}>
                            <Edit className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm">
                            <RotateCcw className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm">
                            <Trash2 className="h-3 w-3 text-red-500" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="teachers" className="space-y-4">
          {/* Search and Filter */}
          <Card>
            <CardContent className="p-4">
              <div className="flex gap-4">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索教师姓名或工号..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                <Select value={selectedDepartment} onValueChange={setSelectedDepartment}>
                  <SelectTrigger className="w-48">
                    <SelectValue placeholder="选择院系" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部院系</SelectItem>
                    <SelectItem value="计算机科学学院">计算机科学学院</SelectItem>
                    <SelectItem value="数学学院">数学学院</SelectItem>
                    <SelectItem value="外语学院">外语学院</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* Teachers Table */}
          <Card>
            <CardHeader>
              <CardTitle>教师列表</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>工号</TableHead>
                    <TableHead>姓名</TableHead>
                    <TableHead>院系</TableHead>
                    <TableHead>职称</TableHead>
                    <TableHead>邮箱</TableHead>
                    <TableHead>入职日期</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead>操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredTeachers.map((teacher) => (
                    <TableRow key={teacher.id}>
                      <TableCell className="font-medium">{teacher.teacherId}</TableCell>
                      <TableCell>{teacher.name}</TableCell>
                      <TableCell>{teacher.department}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{teacher.title}</Badge>
                      </TableCell>
                      <TableCell className="text-sm">{teacher.email}</TableCell>
                      <TableCell>{teacher.hireDate}</TableCell>
                      <TableCell>{getStatusBadge(teacher.status)}</TableCell>
                      <TableCell>
                        <div className="flex space-x-2">
                          <Button variant="ghost" size="sm">
                            <Eye className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => {
                            setEditingUser(teacher);
                            setShowUserForm(true);
                          }}>
                            <Edit className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm">
                            <RotateCcw className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm">
                            <Trash2 className="h-3 w-3 text-red-500" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* User Form Modal */}
      {showUserForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <Card className="w-full max-w-2xl max-h-[90vh] overflow-auto">
            <CardHeader>
              <CardTitle>
                {editingUser ? '编辑用户' : '新增用户'} - {activeTab === 'students' ? '学生' : '教师'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="userId">
                    {activeTab === 'students' ? '学号' : '工号'}
                  </Label>
                  <Input
                    id="userId"
                    placeholder={activeTab === 'students' ? '请输入学号' : '请输入工号'}
                    defaultValue={editingUser?.studentId || editingUser?.teacherId || ''}
                  />
                </div>
                <div>
                  <Label htmlFor="name">姓名</Label>
                  <Input
                    id="name"
                    placeholder="请输入姓名"
                    defaultValue={editingUser?.name || ''}
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="department">院系</Label>
                  <Select defaultValue={editingUser?.department}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择院系" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="计算机科学学院">计算机科学学院</SelectItem>
                      <SelectItem value="数学学院">数学学院</SelectItem>
                      <SelectItem value="外语学院">外语学院</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="major-title">
                    {activeTab === 'students' ? '专业' : '职称'}
                  </Label>
                  {activeTab === 'students' ? (
                    <Select defaultValue={editingUser?.major}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择专业" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="计算机科学与技术">计算机科学与技术</SelectItem>
                        <SelectItem value="软件工程">软件工程</SelectItem>
                        <SelectItem value="数学与应用数学">数学与应用数学</SelectItem>
                      </SelectContent>
                    </Select>
                  ) : (
                    <Select defaultValue={editingUser?.title}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择职称" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="教授">教授</SelectItem>
                        <SelectItem value="副教授">副教授</SelectItem>
                        <SelectItem value="讲师">讲师</SelectItem>
                      </SelectContent>
                    </Select>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="email">邮箱</Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="请输入邮箱地址"
                    defaultValue={editingUser?.email || ''}
                  />
                </div>
                <div>
                  <Label htmlFor="phone">手机号</Label>
                  <Input
                    id="phone"
                    placeholder="请输入手机号"
                    defaultValue={editingUser?.phone || ''}
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="status">账户状态</Label>
                <Select defaultValue={editingUser?.status || 'active'}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">正常</SelectItem>
                    <SelectItem value="inactive">停用</SelectItem>
                    {activeTab === 'students' && <SelectItem value="suspended">暂停</SelectItem>}
                  </SelectContent>
                </Select>
              </div>

              <div className="flex gap-2 pt-4">
                <Button className="flex-1">
                  {editingUser ? '更新' : '创建'}用户
                </Button>
                <Button variant="outline" onClick={() => {
                  setShowUserForm(false);
                  setEditingUser(null);
                }}>
                  取消
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}